/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author marcelo
 */
public class Cliente extends Thread implements java.io.Serializable {

    private String ip;
    private Vector lista;
    private String msg;
    private static Socket socket;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private ServerSocket server;

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getip() {
        return this.ip;
    }

    public Vector getlista() {
        return this.lista;
    }

    public void printlista() {
        for (int i = 0; i < this.lista.size(); i++) {
            System.out.println(lista.get(i));
        }
    }

    //Ao rodar Client, fazer primeira conexao com server p/ atualizar nos
    public static void main(String[] args) throws ClassNotFoundException, IOException {
        BufferedReader terminal;
        InputStreamReader stdin;
        stdin = new InputStreamReader(System.in); //Inicia Buffer de leitura de teclado
        terminal = new BufferedReader(stdin);
        String opt;
        Cliente cli = new Cliente();
        ObjectInputStream entrada;
        ObjectOutputStream saida;

        //Cria um socket com IP e porta sendo primeiro e segundo parametro
        //conexão com servidor
        //socket = new Socket(args[0], Integer.parseInt(args[1]));
        socket = new Socket("frontend", 9092);

        saida = new ObjectOutputStream(socket.getOutputStream());
        cli.setIp(socket.getLocalAddress().toString());
        cli.setlista();
        saida.writeObject("NovaConexao");
        saida.flush();
        saida.writeObject(cli);
        saida.flush();

        cli.start();
        menu();
        opt = terminal.readLine();

        //opt = "2";
        while (!opt.equalsIgnoreCase("6")) {

            switch (opt) {
                case "1":

                    //Adicionar novo arquivo                    
                    socket = new Socket("frontend", 9092);
                    saida = new ObjectOutputStream(socket.getOutputStream());

                    //Pegando path das classes
                    String path;
                    URL main = Cliente.class.getResource("Cliente.class");
                    path = main.getPath();
                    int tam = path.length();
                    path = path.substring(0, (tam - 13));
                    //System.out.println(path);

                    String nomearq;
                    System.out.println("Digite nome do arquivo:");
                    nomearq = terminal.readLine();
                    //nomearq = "teste.txt";
                    PrintWriter writer = new PrintWriter(path + nomearq, "UTF-8");
                    String texto;

                    System.out.println("Digite conteudo de arq:");
                    texto = terminal.readLine();
                    writer.println(texto);
                    writer.close();

                    System.out.println("Atualizar");
                    saida.writeObject("Atualizar");
                    saida.flush();

                    cli.resetlista();
                    cli.setlista();

                    saida.writeObject(cli);
                    saida.flush();

                    break;

                case "2":
                    //Leitura de arquivo
                    String path3;
                    URL main3 = Cliente.class.getResource("Cliente.class");
                    path3 = main3.getPath();
                    int tam3 = path3.length();
                    path3 = path3.substring(0, (tam3 - 13));
                    //System.out.println(path);

                    String nomearq3;

                    System.out.println("Digite nome do arquivo:");
                    nomearq3 = terminal.readLine();
                    File arqteste = new File(path3 + nomearq3);

                    
                    //Teste para evitar erros de acesso ao mesmo tempo de um arquivo
                    if (arqteste.canRead()) {
                        try {
                            BufferedReader in;
                            in = new BufferedReader(new FileReader(path3 + nomearq3));
                            String str;
                            while (in.ready()) {
                                str = in.readLine();
                                System.out.println(str);
                            }
                            in.close();
                        } catch (IOException e) {
                        }
                    }

                case "3":
                    socket = new Socket("frontend", 9092);
                    saida = new ObjectOutputStream(socket.getOutputStream());

                    String path2;
                    URL main2 = Cliente.class.getResource("Cliente.class");
                    path2 = main2.getPath();
                    int tam2 = path2.length();
                    path2 = path2.substring(0, (tam2 - 13));
                    System.out.println(path2);
                    String nomearq2;

                    System.out.println("Digite nome do arquivo:");
                    nomearq2 = terminal.readLine();
                    //nomearq2 = "New Text Document.txt";

                    File f = new File(path2 + nomearq2);

                    // Make sure the file or directory exists and isn't write protected
                    if (f.exists()) {
                        //Teste para evitar erros de acesso ao mesmo tempo de um arquivo
                        if (f.canExecute()) {
                            System.out.println("Arquivo deletado!");
                            boolean success = f.delete();
                        }
                    } else {
                        saida.writeObject("Erro");
                        saida.flush();
                        break;
                    }

                    System.out.println("Atualizar");
                    saida.writeObject("Atualizar");
                    saida.flush();

                    cli.resetlista();
                    cli.setlista();

                    saida.writeObject(cli);
                    saida.flush();

                    break;

                case "4":
                    //Download
                    socket = new Socket("frontend", 9092);
                    String node;
                    File arquivo_transf;
                    saida = new ObjectOutputStream(socket.getOutputStream());

                    System.out.println("Digite nome do arquivo:");
                    nomearq = terminal.readLine();

                    saida.writeObject("Download");
                    saida.flush();
                    saida.writeObject(nomearq);
                    saida.flush();

                    ServerSocket serverresp;
                    serverresp = new ServerSocket(9093);
                    Socket socket2;
                    socket2 = serverresp.accept();
                    entrada = new ObjectInputStream(socket2.getInputStream()); //Buffer de recebimento dados

                    node = (String) entrada.readObject();
                    System.out.println(node);

                    System.out.println("Inicio de transferencia");
                    ObjectOutputStream saida_transf;
                    ObjectInputStream entrada_transf;
                    Socket socket_transf;
                    socket_transf = new Socket(node, 9095);

                    saida_transf = new ObjectOutputStream(socket_transf.getOutputStream());
                    saida_transf.writeObject("Transf");
                    saida_transf.flush();
                    saida_transf.writeObject(nomearq);
                    saida_transf.flush();

                    //Passagem do arquivo e conteudo por sockets
                    String caminho;
                    URL main4 = Cliente.class.getResource("Cliente.class");
                    caminho = main4.getPath();
                    int tam4 = caminho.length();
                    caminho = caminho.substring(0, (tam4 - 13));
                    entrada_transf = new ObjectInputStream(socket_transf.getInputStream());
                    String msg1 = (String) entrada_transf.readObject();
                    System.out.println(msg1);
                    PrintWriter writer2;
                    writer2 = new PrintWriter(caminho + msg1, "UTF-8");
                    String msg2 = (String) entrada_transf.readObject();
                    System.out.println(msg2);
                    writer2.println(msg2);
                    writer2.close();

                    System.out.println("Atualizar");
                    saida.writeObject("Atualizar");
                    saida.flush();

                    cli.resetlista();
                    cli.setlista();
                    
                    saida.writeObject(cli);
                    saida.flush();

                    break;

                case "5":
                    //Editar
                    socket = new Socket("frontend", 9092);
                    saida = new ObjectOutputStream(socket.getOutputStream());
                    System.out.println("Digite nome do arquivo:");
                    nomearq = terminal.readLine();

                    //Pegando path das classes
                    main = Cliente.class.getResource("Cliente.class");
                    path = main.getPath();
                    tam = path.length();
                    path = path.substring(0, (tam - 13));
                    //System.out.println(path);
                    writer = new PrintWriter(path + nomearq, "UTF-8");

                    System.out.println("Digite conteudo de arq:");
                    texto = terminal.readLine();
                    writer.println(texto);
                    writer.close();

                    saida.writeObject("AtualizarConteudo");
                    saida.flush();
                    saida.writeObject(nomearq);
                    saida.flush();
                    saida.writeObject(texto);
                    saida.flush();
                    break;
            }
            menu();
            opt = terminal.readLine();
        }

    }

    @Override
    public void run() {
        try {
            // Modo server para realizar transferencia de arquivos
            long inicio = System.currentTimeMillis();
            ServerSocket server_node;
            Socket socket_node;
            ObjectInputStream entrada_arq;
            ObjectOutputStream saida_arq;
            String arq;
            server_node = new ServerSocket(9095);
            while (true) {

                String msg_node;

                socket_node = server_node.accept();
                entrada_arq = new ObjectInputStream(socket_node.getInputStream());
                msg_node = (String) entrada_arq.readObject();
                switch (msg_node) {
                    case "Transf":
                        arq = (String) entrada_arq.readObject();
                        System.out.println("Nome do arq:" + arq);

                        String path;
                        URL main = Cliente.class.getResource("Cliente.class");
                        path = main.getPath();
                        int tam = path.length();
                        path = path.substring(0, (tam - 13));
                        File arquivo = new File(path + arq);
                        System.out.println(path + arq);

                        saida_arq = new ObjectOutputStream(socket_node.getOutputStream());
                        saida_arq.writeObject(arquivo.getName());
                        saida_arq.flush();

                        try {
                            BufferedReader in = new BufferedReader(new FileReader(path + arq));
                            String str;
                            while (in.ready()) {
                                str = in.readLine();
                                saida_arq.writeObject(str);
                                saida_arq.flush();
                                System.out.println(str);
                            }
                            in.close();
                        } catch (IOException e) {
                        }

                        long fim = System.currentTimeMillis();

                        System.out.println("Tempo de Upload: " + (fim - inicio) + " milisegundos");
                        //saida = new ObjectOutputStream(socket.getOutputStream());                            
                        break;

                    case "AtualizarFiles":
                        arq = (String) entrada_arq.readObject();
                        String txt=(String) entrada_arq.readObject();
                        

                        main = Cliente.class.getResource("Cliente.class");
                        path = main.getPath();
                        tam = path.length();
                        path = path.substring(0, (tam - 13));
                        System.out.println(path + arq);
                        PrintWriter writer = new PrintWriter(path + arq, "UTF-8");

                        writer.println(txt);
                        writer.close();
                        
                        
                        break;
                }

            }
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void menu() {
        System.out.println("1 - Adicionar");
        System.out.println("2 - Leitura");
        System.out.println("3 - Remover");
        System.out.println("4 - Download");
        System.out.println("5 - Editar");
        System.out.println("6 - Sair");
        System.out.println("Escolha uma opcao:");
    }

    public void setlista() {
        // Directory path here
        this.lista = new Vector();
        String path;
        URL main = Cliente.class.getResource("Cliente.class");
        path = main.getPath();
        int tam = path.length();
        path = path.substring(0, (tam - 14));
        System.out.println(path);
        String files;
        File folder = new File(path);

        //path = folder.getAbsolutePath();
        System.out.println();
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                files = listOfFiles[i].getName();
                if (files.endsWith(".txt") || files.endsWith(".TXT")) {
                    System.out.println(files);
                    this.lista.add(files);
                }
            }
        }
    }

    public void resetlista() {
        this.lista.clear();
    }

}
